package com.jokesoft.feedback.core.repository;

import java.sql.Timestamp;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.joda.time.LocalDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.jokesoft.feedback.core.entity.FeedBackEntity;

@Repository
public class FeedBackRepositoryImpl implements FeedBackRepository {

    private static final Logger LOGGER = LoggerFactory.getLogger(FeedBackRepositoryImpl.class);

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    @Transactional
    public void insertFeedBack(String name, String email, String feedBack) {

        FeedBackEntity feedBackEntity = new FeedBackEntity();

        LocalDateTime timeStamp = new LocalDateTime();

        feedBackEntity.setCreationTime(Timestamp.valueOf(convertSeparators(timeStamp.toString())));
        feedBackEntity.setName(name);
        feedBackEntity.setEmail(email);
        feedBackEntity.setFeedBack(feedBack);

        entityManager.persist(feedBackEntity);

        LOGGER.info("Insert feedback = {}", feedBackEntity);

    }

    static String convertSeparators(String input) {
        char[] chars = input.toCharArray();
        chars[10] = ' ';
        return new String(chars);
    }

}
